package com.wulis.seckill.common.util;

import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.*;

/**
 * 创建线程池
 */
public class ThreadPoolUtil {

    private static Integer corePoolSize = Runtime.getRuntime().availableProcessors();

    /**
     * 创建ThreadPoolExecutor有界的任务队列线程池
     *
     * @return
     */
    public static ThreadPoolExecutor getBoundedThreadPool() {
        return getBoundedThreadPool(corePoolSize, 100000);
    }

    public static ThreadPoolExecutor getBoundedThreadPool(Integer capacity) {
        return getBoundedThreadPool(corePoolSize, capacity);
    }

    public static ThreadPoolExecutor getBoundedThreadPool(Integer corePoolSize, Integer capacity) {
        ThreadFactory springThreadFactory =
                new CustomizableThreadFactory("springThread-pool-" + new Thread().getName());

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                corePoolSize + 1,
                10l,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue(capacity),
                springThreadFactory,
                new ThreadPoolExecutor.DiscardOldestPolicy());
        return threadPoolExecutor;
    }

}
